package cn.wwcyc.service.impl;

import cn.wwcyc.domain.Rolemenu;
import cn.wwcyc.domain.TjRolegroup;
import cn.wwcyc.domain.User;
import cn.wwcyc.mapper.RolemenuMapper;
import cn.wwcyc.mapper.TjRolegroupMapper;
import cn.wwcyc.mapper.UserMapper;
import cn.wwcyc.service.RolemenuService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.wwcyc.domain.Role;
import cn.wwcyc.service.RoleService;
import cn.wwcyc.mapper.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* @author z
* @description 针对表【ROLE】的数据库操作Service实现
* @createDate 2023-10-22 10:04:12
*/
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
    implements RoleService{

    @Autowired
    RolemenuMapper rolemenuMapper;
    @Autowired
    TjRolegroupMapper tjRolegroupMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    UserMapper userMapper;

    @Override
    @Transactional
    public Integer removeRoleById(Long id) {
        //删除本角色所有的菜单项
        QueryWrapper<Rolemenu> qw = new QueryWrapper<>();
        qw.eq("roleid", id);
        rolemenuMapper.delete(qw);
        //将拥有该角色的用户角色置空
//        QueryWrapper<User> qw1 = new QueryWrapper<>();
//        qw.eq("roleid", id);
        userMapper.setUserRoleidNull(id);
        Integer i = roleMapper.deleteById(id);
        return i;
    }

    @Override
    @Transactional
    public void setRoleMenuGroup(Long roleId, List<Long> menuGroupIds, List<Long> selmenuIds, List<Long> allmenuIds) {

        QueryWrapper<TjRolegroup> qw1 = new QueryWrapper<>();
        qw1.eq("roleid", roleId);
        tjRolegroupMapper.delete(qw1);
        if (menuGroupIds != null && menuGroupIds.size() > 0) {
            for (Long menuGroupId : menuGroupIds) {
                TjRolegroup tjRolegroup = new TjRolegroup();
                tjRolegroup.setRoleid(roleId);
                tjRolegroup.setGroupid(menuGroupId);
                tjRolegroupMapper.insert(tjRolegroup);
            }
        }
        if (selmenuIds != null && selmenuIds.size() > 0){
            for(int i=0;i<allmenuIds.size();i++){
                QueryWrapper<Rolemenu> qw = new QueryWrapper<>();
                qw.eq("roleid", roleId);
                qw.eq("menuid", allmenuIds.get(i));
                rolemenuMapper.delete(qw);
            }
        }
        if (selmenuIds != null && selmenuIds.size() > 0) {
            for (Long menuId : selmenuIds) {
                Rolemenu rolemenu = new Rolemenu();
                rolemenu.setRoleid(roleId);
                rolemenu.setMenuid(menuId);
                rolemenuMapper.insert(rolemenu);
            }
        }

    }
}




